<?php

namespace App\Admin\Controllers;

use App\Models\StickyTopic;
use Encore\Admin\Http\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Table;
use Encore\Admin\Show;

class StickyTopicController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '置顶帖';

    /**
     * Make a grid builder.
     *
     * @return Table
     */
    protected function table()
    {
        $table = new Table(new StickyTopic());

        $table->model()->with('topic', 'topic.mainFloor', 'topic.mainFloor.detail')->withTrashed();

        $table->column('id', 'ID');
        $table->column('帖子')->display(function () {
            return sprintf(
                '[%s]<a href="%s" target="_blank">%s</a>',
                $this->tid, route('admin.topic.show', [$this->tid]), $this->topic->title_excerpt
            );
        });
        $table->column('位置')->display(function () {
            return $this->position_text;
        });
        $table->column('display_order', '展示顺序');
        $table->column('created_at', '创建时间');
        $table->column('状态')->display(function () {
            return $this->trashed() ? '删除' : '正常';
        });

        $table->actions(function (Actions $actions) {
            $row = $actions->row;
            if ($row->trashed()) {
                $actions->disableDelete(true);
                $actions->add(new Restore());
            } else {
                $actions->disableDelete(false);
            }

        });

        return $table;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(StickyTopic::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('tid', __('Tid'));
        $show->field('position', __('Position'));
        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));
        $show->field('display_order', __('Display order'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new StickyTopic());

        $form->number('tid', '帖子 ID')->rules('required');
        $form->checkbox('position', '位置')->options(StickyTopic::$positionText)->rules('required');
        $form->number('display_order', '展示顺序')->default(0);

        return $form;
    }
}
